package com.aiwu.utils

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Environment
import androidx.documentfile.provider.DocumentFile
import com.aiwu.library.util.MarketGamePathUtil
import org.citra.citra_emu.model.Game
import org.citra.citra_emu.utils.Log
import java.io.File
import java.util.Locale

object CitraUtil {
    //平台名
    const val PLATFORM_3DS = "3DS"
    const val EMU_ROOT_DIR_NAME = "citra-emu"
    const val GAME_DIR_PATH_SHORT = "${MarketGamePathUtil.GAME_DIR_PATH_SHORT_PREFIX}${PLATFORM_3DS}"

    /**
     * 爱吾的游戏文件
     */
    fun get25GameDir(): String {
        val sdcardPath = MarketGamePathUtil.getMarketDownloadSdcardPath()
        return "${sdcardPath}/${MarketGamePathUtil.getGameDirPath(PLATFORM_3DS)}"
    }

    /**
     * 模拟器根目录 兼容其他模拟器以及旧版本游戏数据，继续使用citra-emu文件夹
     */
    fun getEmuRootDirFile(): File {
        return File(Environment.getExternalStorageDirectory(), EMU_ROOT_DIR_NAME)
    }

    //密钥文件夹
    fun getAesKeysDirPath(): String {
        return File(getEmuRootDirFile(), "sysdata").absolutePath
    }

    //即时存档
    fun getStateDir(): String {
        return File(getEmuRootDirFile(), "states").absolutePath
    }

    fun getSDMCDirectory(): String {
        return File(getEmuRootDirFile(), "sdmc").absolutePath
    }

    fun getApplicationDirectory(): String {
        return File(
            getSDMCDirectory(),
            "/Nintendo 3DS/00000000000000000000000000000000/00000000000000000000000000000000/title"
        ).absolutePath
    }

    fun getSystemTitleDirectory(): String {
        return File(
            getEmuRootDirFile(),
            "/nand/00000000000000000000000000000000/title"
        ).absolutePath
    }

    /**
     * 模拟器根目录的SAF路径。必须为主SD卡的"citra-emu"文件夹
     * 短的：content://com.android.externalstorage.documents/tree/primary%3Acitra-emu
     * 长的：content://com.android.externalstorage.documents/tree/primary%3Acitra-emu/document/primary%3Acitra-emu
     * @param isShortType 是否短的类型
     */
    fun getEmuRootDirSAFPath(isShortType: Boolean): String {
        return MarketGamePathUtil.getDirPathSAF(
            MarketGamePathUtil.SAF_DEFAULT_SDCARD_NAME,
            EMU_ROOT_DIR_NAME, isShortType
        )
    }

    fun getEmuRootDirSAFUri(isShortType: Boolean = false): Uri =
        Uri.parse(getEmuRootDirSAFPath(isShortType))

    /**
     * 是否有游戏文件夹的读取权限
     */
    fun hasGameDirReadAccess(context: Context, gameDirUriStr: String): Boolean {
        try {
            if (!PrefsHelper.instance.getAllGameDirectory().contains(gameDirUriStr)) {
                return false
            }
            if (gameDirUriStr.isEmpty() || !gameDirUriStr.endsWith(GAME_DIR_PATH_SHORT, true)
            ) {
                return false
            }

            val uri = Uri.parse(gameDirUriStr)
            val takeFlags =
                Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
            context.contentResolver.takePersistableUriPermission(uri, takeFlags)
            val root = DocumentFile.fromTreeUri(context, uri)
            if (root != null && root.exists()) {
                return true
            }

            context.contentResolver.releasePersistableUriPermission(uri, takeFlags)
        } catch (e: Exception) {
            Log.error("[CitraUtil]: Cannot check aiwu 3dsGame directory permission, error: " + e.message)
        }
        return false
    }

    /**
     * 游戏文件夹的SAF路径
     * 默认SD卡：content://com.android.externalstorage.documents/tree/primary%3A25game%2FemuGame%2F3DS
     * TF卡：content://com.android.externalstorage.documents/tree/F7FF-BCB4%3A25game%2FemuGame%2F3DS
     * @param isShortType 是否短的类型
     */
    fun getGameDirSAFPath(isShortType: Boolean): String {
        return MarketGamePathUtil.getGameDirPathSAF(PLATFORM_3DS, isShortType)
    }

    fun getGameDirSAFUri(isShortType: Boolean = false): Uri =
        Uri.parse(getGameDirSAFPath(isShortType))

    /**
     * 把游戏文件路径转成SAF的uri
     * @param isShortType 是否短的类型
     */
    fun convertGameFilePath2SafUri(romFile: File, isShortType: Boolean = false): Uri {
        return Uri.parse(MarketGamePathUtil.getFilePathSAF(romFile, isShortType))
    }

    /**
     * 是否是3DS游戏文件的后缀
     */
    fun is3DSExtension(fileExtension: String): Boolean {
        val fileExtensionLow = fileExtension.lowercase(Locale.ROOT)
        return fileExtensionLow.equals("cia", true) || Game.extensions.contains(fileExtensionLow)
    }
}